/*
 * I2C.c
 *
 * Created: 09/03/2012 8:51:58
 *  
 */ 


#include "i2c.h"


void I2C_init()
{
  // ---> Write code here to initialize the TWBR register
  // LM75 clock has be to be lower than 400 kHz (according to LM75 data sheet) 
  // The TWBR must be at least 10 in master mode (Mega32 data book)
  TWBR=100;
  TWSR|=0x03;
}

void I2C_start()
{
  TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
  while ((TWCR & (1<<TWINT)) == 0)
  {}  	
}

void I2C_write(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT) | (1<<TWEN);
  while ((TWCR & (1<<TWINT)) == 0)
  {}	
}

uint8_t I2C_read (uint8_t isLast)
{
  if (isLast == 0) //If we want to read more than 1 byte
    TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
  else             //If we want to read only one byte
    TWCR = (1<<TWINT) | (1<<TWEN);

  while ((TWCR & (1<<TWINT)) == 0)
  {}
  return TWDR;
}

void I2C_stop()
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
}